<?php
#                                                                                 
# author: Cody Sorgenfrey                                       
# (c)2013 South Hill Calvary Chapel                                               
#                                                                               
include_once("mysql/database_info.php");
include_once("mysql/common.php");
include_once("common.php");
connect_select_test("ministryApps");
if ($_POST['vars']){
	$query = "INSERT INTO `ministryAppReplies` VALUES('', '".$_POST['ministry']."', '".mysql_real_escape_string($_POST['vars'])."')";
	if (mysql_query($query)){
		echo "Thank you for submitting your questionnaire, we will review and be in touch shortly.";
	} else {
		echo "Error submitting questionnaire, please contact the web-servant with this: \"".$_POST['vars']."\".";
	}
	$vars = explode("|div|", $_POST['vars']);
	for ($x=0;$x<count($vars);$x++){
		$vars[$x] = explode("|separator|", $vars[$x]);
	}
	for ($x=0;$x<count($vars);$x++){
		$body .= "<b>".$vars[$x][1]."</b><br>".$vars[$x][0]."<br><br>";
	}
	$headers = 'From: webservant@southhillcalvary.org'."\r\n";
	$headers .= 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
	mail("codys@southhillcalvary.org, ".$ministry['contact'], "New ".$_POST['ministry']." ministry application", $body, $headers);
	return 1;
}
if (!$_GET['ministry']){
	printf("<p>Missing ministry parameter...</p>");
	return 0;
} 
$meta_key='app, worship, team, apply, try out, worship team, praise';
$meta_desc="The ministry team's applications at South Hill Calvary Chapel.";
print_html_head("applications" , $meta_key, $meta_desc);
?>
<style type="text/css">
	.incomplete,
	#message{
		background-color: #ffe3e3;
	}
	input,
	textarea{
		margin-bottom: 10px;
	}
	textarea{
		width: 400px;
		max-width: 100%;
		height: 60px;
	}
</style>
<?
	print_java_head(null);
?>
<script type='text/javascript'>
	var timer = null;
	var globalInfo = null;
	$(document).ready(function(){
		parseData();
	});
	function parseData(){
		$.post("mysql/data.php",{
			key: "<?echo crypt("He1sR1sen");?>",
			table: "ministryApps",
			searchField: "ministry",
			searchString: "<?echo $_GET['ministry']?>"
		}, function(res){
			if (res.search("empty") != 0){
				var globalInfo = res.split("|cell|");
				$(".page_title").text(globalInfo[1] + " Ministry Questionnaire");
				$("#welcomeMessage").html(globalInfo[3]);
				var rows = globalInfo[4].split("\n");
				for (x in rows){
					rows[x] = rows[x].split("|div|");
				}
				printForm(rows);
			} else {
				$(".content").text("No questionnaire exists for specified ministry.");
			}
		});
	}
	function printForm(info){
		for (x in info){
			if (info[x][2] == "1"){
				$("#questions").append("<br>");
			}
			$("#questions").append("<span class='noPlaceholder'><br>"+info[x][0]+"<br></span>");
			var str = new String(info[x][1]).match(/\[.+\]/);
			var inputType = new String(info[x][1]).replace(/\[.+\]/, "");
			$("#questions").append("<input placeholder=\""+info[x][0]+"\" class=\"question "+info[x][3]+"\" />");
			$(".question:last").data("custom", {type: inputType, options: str});
		}
		initPage();
	}
	function initPage(){
		var i = 0;
		$(".question").each(function(){
			if ($(this).data("custom").type == "textarea"){
				$(this).replaceWith("<textarea class=\""+$(this).attr("class")+"\" placeholder=\""+$(this).attr("placeholder")+"\"></textarea>");
			} else if ($(this).data("custom").type == "hidden"){
				$(this).prev(".noPlaceholder").remove();
				$(this).replaceWith("<h4>"+$(this).attr("placeholder")+"</h4>");
			} else if (($(this).data("custom").type == "radio") || ($(this).data("custom").type == "checkbox")){
				$("<div class='multiHolder' id='"+i+"'></div>").insertAfter($(this));
				$(".multiHolder:last").append("<p class='multiQuestion'>"+$(this).attr("placeholder")+"</p>");
				var str = $(this).data("custom").options;
				str = new String(str).replace(/\[/, "").replace(/\]/, "").split("|multi|");
				for (x in str){
					$(".multiHolder:last").append("<input type='"+$(this).data("custom").type+"' name='choice"+i+"' class='"+$(this).attr("class")+"' value='"+str[x]+"' > "+str[x]+"<br>");
				}
				$(".noPlaceholder:contains("+$(this).attr("placeholder")+")").remove();
				$(this).remove();
				i++;
			}
		});
	}
	function customSubmit(form){
		$("#message").text("Please wait...");
		var answers = new Array;
		$(".required").each(function(){
			if (($(this).attr("type") == "radio") || ($(this).attr("type") == "checkbox")){
				if ($("[name='"+$(this).attr("name")+"']:checked").length == 0){
					$("[name='"+$(this).attr("name")+"']").prev(".multiQuestion").addClass("incomplete");
				} else {
					$("[name='"+$(this).attr("name")+"']").prev(".multiQuestion").removeClass("incomplete");
				}
			} else {
				if (!$(this).val()){
					$(this).addClass("incomplete");
				} else {
					$(this).removeClass("incomplete");
				}
			}
		});
		if ($(".incomplete").length == 0){
			if ($("#validate").val() == "SUBMIT"){
				$(".question").each(function(){
					if (($(this).attr("type") == "radio") || ($(this).attr("type") == "checkbox")){
						var multi = new Array;
						$("[name='"+$(this).attr("name")+"']:checked").each(function(){
							multi.push($(this).val());
						});
						multi = multi.join(", ");
						multi = multi+"|separator|"+$(this).siblings(":first").text();
						if ($.inArray(multi , answers) == -1){
							answers.push(multi);
						}
					} else {
						answers.push($(this).val()+"|separator|"+$(this).attr("placeholder"));
					}
				});
				$.post("/application.php", {
					ministry: "<?echo $_GET['ministry'];?>",
					vars: answers.join("|div|")
				}, function(res){
					$(".content").html(res);
				});
			} else {
				$("#message").text("Please type \"SUBMIT\" in the box above.");
			}
		} else {
			$("#message").text("Oops! You're not done filling out this page!");
		}
	}
</script>
<?
	begin_body();
	page_title_no_content("Ministry Questionnaire");
?>
<div class="content">
	<p id='welcomeMessage'></p>
	<div id='questions'></div>
	<br>
	Please type the word "SUBMIT" in all capital letters to continue. <input type='text' id='validate' class="required">
	<br>
	<button onclick='(event.preventDefault) ? event.preventDefault() : event.returnValue=false; customSubmit();'>Submit</button>
	<span id='message'></span>
<?
end_page_title();
end_body();
?>